package com.rong.mbt.personal.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.calanger.hh.entity.ResultView;
import com.calanger.hh.model.Doctor;
import com.calanger.hh.model.OrderPre;
import com.calanger.hh.model.User;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.activity.ArticleDetailsActivity;
import com.rong.mbt.personal.activity.DoctorInfomationActivity;
import com.rong.mbt.personal.activity.DoctorListSimpleActivity;
import com.rong.mbt.personal.activity.PatientDetailActivity;
import com.rong.mbt.personal.activity.UserViewLikeCommentActivity;
import com.rong.mbt.personal.adapter.IndexArticleListAdapter;
import com.rong.mbt.personal.adapter.OrderListAdapter;
import com.rong.mbt.personal.adapter.OrderPreListAdapter;
import com.rong.mbt.personal.adapter.UserViewLikeCommentAdapter;
import com.rong.mbt.personal.bean.article.ArticleItemBean;
import com.rong.mbt.personal.bean.article.ArticleListPageBean;
import com.rong.mbt.personal.http.UrlApi;
import com.rong.mbt.personal.http.callback.JsonCallback;
import com.rong.mbt.personal.utils.SpUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;

/**
 * 文章列表
 */
public class OrderPreItemFragment extends Fragment implements OnRefreshLoadMoreListener {

    private String mTitle;
    private Integer code = 0;
    private Integer mode = 0;
    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mRefreshLayout;
    private OrderPreListAdapter orderPreListAdapter;
    private UserViewLikeCommentAdapter userViewLikeCommentAdapter;
    private int pageNumber = 1;
    private List<Map<String,Object>> initData = new ArrayList<Map<String,Object>>();
    private boolean freshOrMore = false;
    private int total_count = 0;

    public static OrderPreItemFragment getInstance(String title, Integer code) {
        OrderPreItemFragment sf = new OrderPreItemFragment();
        sf.mTitle = title;
        sf.code = code;
        return sf;
    }

    public static OrderPreItemFragment getInstance(String title, Integer code, Integer mode) {
        OrderPreItemFragment sf = new OrderPreItemFragment();
        sf.mTitle = title;
        sf.code = code;
        sf.mode = mode;
        return sf;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_smart_refresh_layout, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);

        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        orderPreListAdapter = new OrderPreListAdapter();
        userViewLikeCommentAdapter = new UserViewLikeCommentAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(orderPreListAdapter);
        orderPreListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Map<String,Object> item = (Map<String,Object>) adapter.getItem(position);
                JSONObject jsonMap = new JSONObject(item);
                OrderPre orderPre = jsonMap.getObject("orderPre", OrderPre.class);
                startActivity(new Intent(getActivity(), PatientDetailActivity.class).putExtra("id", orderPre.getId()));
            }
        });

        orderPreListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Map<String,Object> item = (Map<String,Object>) adapter.getItem(position);
                JSONObject jsonMap = new JSONObject(item);
                OrderPre orderPre = jsonMap.getObject("orderPre", OrderPre.class);
                User user = jsonMap.getObject("user", User.class);
                Doctor doctor = jsonMap.getObject("doctor", Doctor.class);
                if(view.getId()==R.id.tv_cancel_order_pre){
                    OkGo.<ResultView>get(UrlApi.orderPreRemove)
                            .tag(this)
                            .headers("mbtToken", SpUtils.getToken(getActivity()))
                            .params("id", orderPre.getId())
                            .execute(new JsonCallback<ResultView>() {
                                @Override
                                public void onSuccess(Response<ResultView> response) {
                                    Log.i(getActivity().toString(), "onSuccess  " + response.body());
                                    ResultView resultView = response.body();
                                    if (resultView.getResultCode() == 0) {
                                        Toast.makeText(getActivity(), "操作成功", Toast.LENGTH_SHORT).show();
                                        requestArticle();
                                    } else {
                                        Toast.makeText(getActivity(), resultView.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                }
                if(view.getId()==R.id.tv_quick_communication){
                    RongIM.getInstance().startPrivateChat(getActivity(), doctor.getUserId() + "", doctor.getName());
                }
                if(view.getId()==R.id.tv_confirm_completion){
                    OkGo.<ResultView>get(UrlApi.orderPreUpdate)
                            .tag(this)
                            .headers("mbtToken", SpUtils.getToken(getActivity()))
                            .params("id", orderPre.getId())
                            .params("orderStatus", 2)
                            .execute(new JsonCallback<ResultView>() {
                                @Override
                                public void onSuccess(Response<ResultView> response) {
                                    Log.i(getActivity().toString(), "onSuccess  " + response.body());
                                    ResultView resultView = response.body();
                                    if (resultView.getResultCode() == 0) {
                                        Toast.makeText(getActivity(), "操作成功", Toast.LENGTH_SHORT).show();
                                        requestArticle();
                                    } else {
                                        Toast.makeText(getActivity(), resultView.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                }
                if(view.getId()==R.id.tv_comment){
                    OkGo.<ResultView>get(UrlApi.userViewLikeCommentList)
                            .tag(this)
                            .headers("mbtToken", SpUtils.getToken(getActivity()))
                            .params("objId",orderPre.getId())
                            .params("objType",3)
                            .params("type",2)
                            .params("pageNumber", 5)
                            .execute(new JsonCallback<ResultView>() {
                                @Override
                                public void onSuccess(Response<ResultView> response) {
                                    Log.i(getActivity().toString(), "onSuccess  " + response.body());
                                    ResultView resultView = response.body();
                                    if (resultView.getData() != null&&resultView.getResultCode()==0) {
                                        total_count = resultView.getCount();
                                        List<Map<String,Object>> data = (List<Map<String, Object>>) resultView.getData();
                                        userViewLikeCommentAdapter = new UserViewLikeCommentAdapter();
                                        userViewLikeCommentAdapter.setNewData(data);
                                        RecyclerView rv = getActivity().findViewById(R.id.recycler_view_order_pre_comment);
                                        rv.setAdapter(userViewLikeCommentAdapter);
                                    } else {
                                        Toast.makeText(getActivity(), resultView.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });


                }
            }
        });
        userViewLikeCommentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if(view.getId()==R.id.tv_user_like){
                    ImageView iv = view.findViewById(R.id.tv_user_like);
                    iv.setBackground(getResources().getDrawable(R.drawable.abc_patient_personal_buttom4_01));
                }
                if(view.getId()==R.id.tv_user_comment){
                    //弹窗插件
                }
            }
        });
        requestArticle();
    }

    private void requestArticle() {
        int categoryId = code;
        OkGo okGo = OkGo.getInstance();
        HttpParams commonParams = new HttpParams();
        if (code == 0) {
            commonParams.put("orderStatus", 0);
        }else if(code==1){
            commonParams.put("orderStatus", 1);
        }else if(code==2){
            commonParams.put("orderStatus", 2);
        }else{
//全部查询
        }
        okGo.addCommonParams(commonParams);
//        if(mode==1){
//            commonParams.put("userid", SpUtils.getDoctorId(getActivity()));
//        }
            //文章列表
        okGo.<ResultView>get(UrlApi.orderPreListByPage)
                    .tag(this)
                    .headers("mbtToken", SpUtils.getToken(getActivity()))
                    .params("pageNumber", pageNumber)
                    .execute(new JsonCallback<ResultView>() {
                        @Override
                        public void onSuccess(Response<ResultView> response) {
                            if (response != null && response.body() != null) {
                                ResultView resultView = response.body();
                                if (resultView.getData() != null&&resultView.getResultCode()==0) {
                                    total_count = resultView.getCount();
                                    List<Map<String,Object>> data = (List<Map<String, Object>>) resultView.getData();

                                    if (freshOrMore) {
                                        if(initData.size()>= total_count){
                                            mRefreshLayout.finishLoadMore();
                                        }else{
                                            initData.addAll(data);
                                        }
                                        freshOrMore = false;
                                        orderPreListAdapter.setNewData(initData);
                                        mRefreshLayout.finishLoadMore();
                                    } else {
                                        initData = data;
                                        orderPreListAdapter.setNewData(initData);
                                        mRefreshLayout.finishRefresh();
                                    }
                                }
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.finishLoadMore();
                            }
                        }
                    });


    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        pageNumber++;
        freshOrMore = true;
        requestArticle();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNumber = 1;
        requestArticle();
    }
}
